import datetime
import json
import base64
import os

from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer
from django.conf import settings

from .models import Message


class ChatConsumer(WebsocketConsumer):

    def __init__(self, *args, **kwargs):
        super().__init__(args, kwargs)
        self.room_group_name = None
        self.room_name = None

    def connect(self):
        self.room_name = self.scope["url_route"]["kwargs"]["room_name"]
        self.room_group_name = "chat_%s" % self.room_name

        # 计入聊天室
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name, self.channel_name
        )
        self.accept()

    def disconnect(self, close_code):
        # Leave room group
        async_to_sync(self.channel_layer.group_discard)(
            self.room_group_name, self.channel_name
        )

    # Receive message from WebSocket
    def receive(self, text_data, bytes_data=None):
        data = json.loads(text_data)
        message_type = data.get('type', None)

        if message_type == 'text':
            self.receive_text_message(data)
        elif message_type == 'image':
            self.receive_image_message(data)

    def receive_text_message(self, data):
        """接收文字消息"""
        # Handle regular text message
        message = data['message']
        username = data['username']
        room = data['room']

        # 保存本条信息到模型层
        self.save_msg(username, room, message)
        print(f"Received message:{message} from user '{username}'")
        # Send message to room group
        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name, {"type": "chat_message", "message": message, "username": username}
        )

    def receive_image_message(self, data):
        """接收图片消息"""
        # 处理接收到的图片消息
        image_data = data['image']  # 图片数据（Base64 编码的字符串）
        username = data['username']  # 发送图片的用户名
        room = data['room']  # 房间名
        print(f'receive_image_message: [姓名:{username} 房间:{room} 信息:<图片信息> ]')
        # 解码 Base64 图片数据
        image_data = base64.b64decode(image_data)
        # 获取当前时间戳
        current_timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
        # 生成图片文件名
        image_filename = f"{current_timestamp}.png"
        save_path = os.path.join(settings.MEDIA_ROOT, image_filename)
        print(f'receive_text_message: [存储路径: {save_path} ]')
        # 将图片数据保存为文件
        with open(save_path, "wb") as f:
            f.write(image_data)

        # 将图片路径保存到 Message 模型的 image 字段
        image = Message.objects.create(username=username, room=room, image=image_filename)
        image.save()
        print(f'receive_text_message: 接收完成!')
        # 向房间中的其他用户广播图片接收通知
        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name, {"type": "chat_image", "message": image_filename,"username":username}
        )

    # Receive message from room group
    def chat_message(self, event):
        """
        接收消息后 此函数转发聊天室消息
        """

        message = event["message"]
        username = event["username"]

        # Send message to WebSocket
        self.send(text_data=json.dumps({"type": "text", "message": message, "username": username}))

    def chat_image(self, event):
        message = event["message"]
        username = event["username"]

        # Send message to WebSocket
        self.send(text_data=json.dumps({"type": "image", "message": message, "username": username}))

    # 保存消息
    def save_msg(self, username, room, msg):
        Message.objects.create(username=username, room=room, content=msg)
